#include "uart_receive_app.h"

static uint8_t  uart1_rx_buffer[UART_RECEIVE_BUFFER_SIZE];

void uart1_start(void){
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, uart1_rx_buffer, UART_RECEIVE_BUFFER_SIZE);
	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx ,DMA_IT_HT);
}


void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    if(huart->Instance == USART1){
         xSemaphoreGiveFromISR(xUart_RXSemaphore, &xHigherPriorityTaskWoken);
    }


    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}

osThreadId_t uart_receive_TaskHandle;
const osThreadAttr_t uart_receive_Task_attributes = {
  .name = "uart_receive_Task",
  .stack_size = UART_RECEIVE_TASK_STACK_SIZE * 4,
  .priority = (osPriority_t) UART_RECEIVE_TASK_PRIORITY,
};

void uart_receive_Task(void *argument)
{
  /* USER CODE BEGIN StartDefaultTask */
  /* Infinite loop */
    uart1_start();
    for(;;)
    {
        if (xSemaphoreTake(xUart_RXSemaphore, portMAX_DELAY) == pdTRUE) {
            // Data processing
            #ifdef DBUG
                printf("UART1 received data: %s\n", uart1_rx_buffer);
            #endif
            memset(uart1_rx_buffer, 0, UART_RECEIVE_BUFFER_SIZE);
            uart1_start();
        }
    }
  /* USER CODE END StartDefaultTask */
}
